package lol.clann.minecraft.springboot.bukkit.plugin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;

/**
 *
 * @author pyz
 * @date 2019/5/13 9:41 PM
 */
public class GlobalEventBus {
    private static final Map<Class, List<Consumer<Object>>> EVENT_BUS = new HashMap<>();

    public static void fire(Object event) {
        List<Consumer<Object>> listeners = EVENT_BUS.get(event.getClass());
        if (listeners != null) {
            for (Consumer<Object> listener : listeners) {
                listener.accept(event);
            }
        }
    }

    public static <T> void register(Class<T> eventClass, Consumer<T> consumer) {
        synchronized (EVENT_BUS) {
            List<Consumer<Object>> listeners = EVENT_BUS.get(eventClass);
            if (listeners == null) {
                listeners = new ArrayList<>();
                EVENT_BUS.put(eventClass, listeners);
            }
            listeners.add((Consumer<Object>) consumer);
        }
    }

    public static <T> void unregister(Class<T> eventClass, Consumer<T> consumer) {
        synchronized (EVENT_BUS) {
            List<Consumer<Object>> listeners = EVENT_BUS.get(eventClass);
            if (listeners == null) {
                return;
            }
            listeners.remove(consumer);
        }
    }

}
